// const AdminModel=require("../../model/AdminModel")
// var sqlConnect = require('../model/connect');
let mysqlpool = require("../../model/connect");
mysqlpool.connect((err)=>{
 if(err) throw err;
 console.log("post:数据库连接成功");
})
//传递username和password
const loginControler=async (request,response)=>{
    //取出表单post传值的值
    let username=request.body.username;
    let password=request.body.password;
    // let res = await AdminModel.find();
    // console.log(res);
    console.log(username,password);
    
    let sql_check = `SELECT * FROM admin_user where username = "${username}"`
    //查找是否有这个用户名
    await mysqlpool.query(sql_check, async function(err,res){
        console.log("res",res);
        //没有就新建用户然后登陆
        if( !res.length ){
            let sql_insert = `insert into admin_user (username,password) values ("${username}","${password}")`;
            await mysqlpool.query(sql_insert, (err,res)=>{
               console.log(res);
            })
            //xyh:新建用户登录 lyh:老用户登陆 dl:登陆 areaMsg:用户填写的社区信息
            response.send({xyh: true, lyh: false, dl: true, msg: "注册登陆成功",areaMsg:{}});
        }
        else{

            // 有就看密码是否正确，正确就登陆
            let sql_check2 = sql_check += `and password = "${password}"`;
            await mysqlpool.query(sql_check2, async function(err,res){
                if( !res.length ){
                    response.send({xyh: false, lyh: false, dl: false, msg: "用户名已存在",areaMsg:{}})
                }
                //查找登陆用户是否填写了社区信息
                else{
                    let sql_check3 = `SELECT * FROM area where username = "${username}"`
                     await mysqlpool.query(sql_check3, (err,res)=>{
                        //  填写了就直接展示填写的信息
                         if( !res.length ){
                            response.send({ xyh: false, lyh: true, dl: true, msg: "登录成功",areaMsg:{} })
                         }
                         //没填写继续展现用户表单提交页面 areaMsg:已填写的社区信息
                         else{
                             let {city,community} = res[0];
                            response.send({xyh: false, lyh: true, dl: true, msg: "登录成功", areaMsg:{city,community}})
                         }
                     })
                } 
                // else response.send({xyh: false, lyh: true, dl: true, msg: "登录成功"})
            })
        }
       
    })
    /* let result=await AdminModel.findOne({email,password});//异步代码 根据邮箱地址和密码查询用户
    console.log("数据库用户信息",result);
    if(result&&result.email==email&&result.status==1){
        //登录成功记录登录用户的信息
        request.session["islogin"]=true;
        request.session["username"]=result.username;
        request.session["email"]=email;
        request.session["role"]=result.role;
        //跳转到后台首页
        response.redirect("/admin/");//302重定向到首页.
    }else if(result&&result.status==0){
        response.redirect("/admin/login?msg=禁止登录")
    }else{
        response.redirect("/admin/login?msg=账号或密码错误")
    } */
}
module.exports=loginControler